package com.yc.thread.pro2_knn.knn;

import com.yc.thread.pro2_knn.bean.BankMarketing;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据加载器：用于读取数据文件data和测试文件test
 *
 * @author zwei
 * @create 2024-07-17 20:04
 */
public class BankMarketingLoader {
    public static List<BankMarketing> load(String path) {
        List<BankMarketing> list = new ArrayList<BankMarketing>();
        //读取path位置的文件，并解析成bankmarketing对象
        //技术：java.io流  File类  InputStream 二进制
        //        =>利用InputStreamReader 字符流包装成Reader  =>BufferedReader 缓冲字符流 .readLine()读一行
        //2.采用线程安全的文件操作
        //BIO: BufferedReader reader=new BufferedReader(new FileReader(new FileInputStream( path) ) );
        //NIO: new FileInputStream(path)=>InputStream iis=Files.newInputStream((path);
        //3.异常处理    try-catch-finally
        //转成jdk8以后  try...resources
        Path p = Paths.get(path);
        try (InputStream inputStream = Files.newInputStream(p);
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        ) {        //()中加入的是可以close()的资源(只要一个类实现Closeable接口)，比如流
            String line=null;
            while ((line=reader.readLine())!=null){
                String data[]=line.split(";");
                BankMarketing bank=new BankMarketing();
                bank.setData(data);
                list.add(bank);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
